//
//  GBChatMatchHeadLoopView.swift
//  APSwift
//
//  Created by jianbo.pei on 2023/6/25.
//

import UIKit
import APExtensions

class GBChatMatchHeadLoopView: APBaseView {
    private var firstLabel: UILabel!
    private var secondLabel: UILabel!
    private var index: Int = 0
    private var timer: Timer?
    
    override func createUI() {
        super.createUI()
        layer.masksToBounds = true
        
        firstLabel = .ap.lb(.ap.regular(13), .ap.hex("BDBFCF")).then({ make in
            addSubview(make)
            make.textAlignment = .center
            make.frame = CGRect(x: 0, y: 0, width: ap_kScreenW, height: 19)
            make.text = "正在为你寻找符合匹配条件的用户"
        })
        
        secondLabel = .ap.lb(.ap.regular(13), .ap.hex("BDBFCF")).then({ make in
            addSubview(make)
            make.textAlignment = .center
            make.frame = CGRect(x: 0, y: 19, width: ap_kScreenW, height: 19)
            make.text = "匹配成功后将通知双方"
        })
    }
    
    override func didMoveToWindow() {
        super.didMoveToWindow()
        if window == nil {
            removeTimer()
        } else {
            addTimer()
        }
    }
    
    private func addTimer() {
        removeTimer()
        if timer == nil {
            timer = Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(loop), userInfo: nil, repeats: true)
            RunLoop.current.add(timer!, forMode: .common)
        }
    }
    
    private func removeTimer() {
        if timer != nil {
            timer?.invalidate()
            timer = nil
        }
    }
    
    @objc private func loop() {
        var firstLbFrame = firstLabel.frame
        var secondLbFrame = secondLabel.frame
        
        if index == 0 {
            index = 1
            secondLbFrame.origin.y = 0
            firstLbFrame.origin.y = -firstLbFrame.size.height
        } else if index == 1 {
            index = 0
            firstLbFrame.origin.y = 0
            secondLbFrame.origin.y = -secondLbFrame.size.height
        }

        UIView.animate(withDuration: 0.33) {
            self.firstLabel.frame = firstLbFrame
            self.secondLabel.frame = secondLbFrame
        } completion: { _ in
            if self.index == 0 {
                secondLbFrame.origin.y = secondLbFrame.size.height
                self.secondLabel.frame = secondLbFrame
            }
            if self.index == 1 {
                firstLbFrame.origin.y = firstLbFrame.size.height
                self.firstLabel.frame = firstLbFrame
            }
        }
    }
}
